package com.atguigu.convertencoding;

import java.io.*;
import java.nio.charset.Charset;

/**
 * @Author: J.K
 * @Date: 2020-07-31 16:59
 * @Description: GBK--->UTF-8 将文件编码由GBK转为UTF-8
 */
public class GbkToUtf {

    private final static String targetFileUrl = "G:\\Java-Practise-Projects\\Algorithm";

    public static void main(String[] args) {
        File file = new File(targetFileUrl);
        GbkToUtf.fileList(file);
    }

    // 遍历目录，将文件从GBK转换成UTF-8
    public static void fileList(File file) {
        File rootFile = file;
        File[] files = rootFile.listFiles();
        if (files != null) {
            for (File f : files) {
                if (!f.isDirectory()) {
                    codeConvert(f);
                }
                System.out.println(f.getPath());
                // 递归调用子文件夹下的文件
                fileList(f);
            }
        }
    }


    public static void codeConvert(File file) {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader
                    (new FileInputStream(file), Charset.forName("GBK")));
            StringBuilder sb = new StringBuilder();
            String str;
            while ((str = br.readLine()) != null) {
                sb.append(str);
                sb.append("\n");
            }
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF-8")));
            bw.write(sb.toString());
            bw.flush();
            bw.close();
            //br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}